/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package phd.dupenois.changeidentifiers.dotpatterns;

import java.util.Vector;

/**
 *
 * @author mpd209
 */
public class DotPatternBuffer implements Cloneable{
    private Vector<DotPattern> buffer;
    private Vector<DotPattern> testBuffer;
    private boolean locked;
    private boolean useTestBuffer;
    public DotPatternBuffer(){
        this.buffer = new Vector<DotPattern>();
        this.useTestBuffer = false;
    }

    public void reset(){
        synchronized(this){
            this.buffer = new Vector<DotPattern>();
            this.useTestBuffer = false;
            this.testBuffer = null;
        }
    }

    public void initialiseTesting(){
        this.testBuffer = new Vector<DotPattern>();
    }
    public void switchBuffers(){
        synchronized(this){
            this.useTestBuffer = (!this.useTestBuffer);
        }
    }
    private boolean usingTestBuffer(){
        return this.useTestBuffer;
    }
    public void add(DotPattern pattern){
        synchronized(this){
            while(this.locked){
                try {
                    Thread.sleep(1);
                } catch (InterruptedException ex) {
                }
            }
            buffer.add(pattern);
            if(this.testBuffer != null) this.testBuffer.add(pattern);
        }
    }

    public boolean hasNext(){
        if(usingTestBuffer()) return (this.testBuffer.size()>0);
        return (buffer.size()>0);
    }
    public int size(){
        if(usingTestBuffer()) return this.testBuffer.size();
        return buffer.size();
    }
    public DotPattern next(){
        synchronized(this){
            DotPattern pattern = null;
            if(hasNext()){
                this.locked = true;
                if(usingTestBuffer()&&hasNext()){
                    pattern = this.testBuffer.remove(0);
                }else{
                    pattern = this.buffer.remove(0);
                }
                this.locked = false;
            }
            return pattern;
        }
    }
    /**
     * 
     * @return
     */
    @Override
    public DotPatternBuffer clone(){
        DotPatternBuffer newBuffer = new DotPatternBuffer();
        if(this.testBuffer!=null) newBuffer.initialiseTesting();
        DotPattern[] patterns = buffer.toArray(new DotPattern[buffer.size()]);
        for(DotPattern pattern : patterns){
            newBuffer.add(pattern);
        }
        return newBuffer;
    }
}
